package extras;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Md5Encryption
 * 
 * @author Mamadou TOURE
 * 
 * The Md5Encryption class provides two methods to encrypt and test passwords.
 * 
 */
public class Md5Encryption 
{
	
	public static void main(String[] args) {
		System.out.println(Md5Encryption.getEncodedPassword(args[0]));
	}
	
	public static String getEncodedPassword(String key)
	{
		StringBuffer hashString = new StringBuffer();
		if(key != null && !key.equals(""))
		{
			byte[] uniqueKey = key.getBytes();
			byte[] hash = null;
			try 
			{
				hash = MessageDigest.getInstance("MD5").digest(uniqueKey);
			} 
			catch (NoSuchAlgorithmException e) 
			{
				 throw new Error("no MD5 support in this VM");
			}
			 
			for ( int i = 0; i < hash.length; ++i )
			{
				String hex = Integer.toHexString(hash[i]);
			 	if ( hex.length() == 1 ) 
			 	{
			 		hashString.append('0');
			 		hashString.append(hex.charAt(hex.length()-1));
				} 
				else 
				{
			 		hashString.append(hex.substring(hex.length()-2));
			 	}
			}
		}
		return hashString.toString();
	 }
	
	 public static boolean testPassword(String clearPassword,String encodedPassword) throws NoSuchAlgorithmException
	 {
		 String encodedTestPassword = Md5Encryption.getEncodedPassword(clearPassword);
		 return (encodedTestPassword.equals(encodedPassword));
	 }
}
